<!-- src/views/SearchResults.vue -->
<template>
  <div class="search-results-container">
    <TopBar :initial-query="searchQuery" />
    <div class="content">
      <MenuLine />
      <div class="search-results">
        <h2>搜索结果：{{ searchQuery || '无关键词' }}</h2>
        <el-row :gutter="30" v-if="newsList.length">
          <el-col
            v-for="news in newsList"
            :key="news.id"
            :span="8"
            class="news-card"
            @click="$router.push(`/news/${news.id}`)"
          >
            <el-card :body-style="{ padding: '0px' }">
              <img
                :src="news.coverUrl || defaultImage"
                class="news-image"
                @error="handleImageError"
              />
              <div class="news-title">
                <span>{{ news.title }}</span>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-empty v-else description="未找到匹配的新闻" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useNewsStore } from '@/stores/news';
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

const route = useRoute();
const router = useRouter();
const newsStore = useNewsStore();

const searchQuery = ref('');
const newsList = ref([]);
const defaultImage = 'https://picsum.photos/400/200?random=0';

const handleImageError = (e: Event) => {
  (e.target as HTMLImageElement).src = defaultImage;
};

onMounted(async () => {
  searchQuery.value = route.query.q?.toString().trim() || '';
  if (!searchQuery.value) {
    ElMessage.warning('请输入搜索关键词');
    newsList.value = [];
    return;
  }
  try {
    const results = await newsStore.searchNews(searchQuery.value);
    newsList.value = results;
  } catch (error: any) {
    ElMessage.error('搜索失败: ' + error.message);
    newsList.value = [];
  }
});
</script>

<style scoped>
.search-results-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 60px;
}

.content {
  padding-top: 60px;
  width: 80%;
  margin: 0 auto;
}

.search-results {
  margin-top: 20px;
}

.search-results h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.news-card {
  margin-bottom: 20px;
  cursor: pointer;
}

.news-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.news-title {
  padding: 14px;
  min-height: 50px;
  display: flex;
  align-items: center;
}

.news-title span {
  font-size: 14px;
  color: #333;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
}
</style>